import 'package:state_beacon/state_beacon.dart';
import '../models/user_data_model.dart';

/// 用户状态管理
class UserState {
  // 静态状态变量
  static UserDataModel? _currentUser;
  // 注意：不使用 final，因为我们需要能够添加新用户和修改现有用户
  static List<UserDataModel> _allUsers = [];
  static bool _isLoggedIn = false;

  // State Beacon 实例
  static final currentUserBeacon = Beacon.writable<UserDataModel?>(
    _currentUser,
  );
  static final allUsersBeacon = Beacon.writable<List<UserDataModel>>(_allUsers);
  static final isLoggedInBeacon = Beacon.writable<bool>(_isLoggedIn);

  /// 初始化默认用户数据
  static void _initializeDefaultUsers() {
    if (_allUsers.isNotEmpty) return; // 避免重复初始化

    _allUsers.addAll([
      UserDataModel(
        userId: 'user_001',
        account: 'admin',
        password: '123456',
        userName: 'Raven',
        signature:
            'Exploring Madagascar\'s unique wildlife, one lemur at a time! 🐒',
        avatar: 'assets/images/avatar1.png',
      ),
      UserDataModel(
        userId: 'user_002',
        account: 'baobab_traveler',
        password: '123456',
        userName: 'Nyx',
        signature: 'Chasing sunsets under ancient baobab trees 🌳',
        avatar: 'assets/images/avatar2.png',
      ),
      UserDataModel(
        userId: 'user_003',
        account: 'chameleon_guide',
        password: '123456',
        userName: 'Orion',
        signature: 'Professional wildlife guide specializing in chameleons 🦎',
        avatar: 'assets/images/avatar3.png',
      ),
      UserDataModel(
        userId: 'user_004',
        account: 'fossa_hunter',
        password: '123456',
        userName: 'Luna',
        signature: 'Documenting Madagascar\'s apex predator adventures 🐱',
        avatar: 'assets/images/avatar4.png',
      ),
      UserDataModel(
        userId: 'user_005',
        account: 'gecko_spotter',
        password: '123456',
        userName: 'Phoenix',
        signature: 'Night safari enthusiast, gecko whisperer 🌙',
        avatar: 'assets/images/avatar5.png',
      ),
      UserDataModel(
        userId: 'user_006',
        account: 'tenrec_explorer',
        password: '123456',
        userName: 'Aria',
        signature: 'Discovering Madagascar\'s spiny treasures 🦔',
        avatar: 'assets/images/avatar6.png',
      ),
      UserDataModel(
        userId: 'user_007',
        account: 'aye_aye_finder',
        password: '123456',
        userName: 'Kai',
        signature: 'Rare aye-aye encounters and conservation efforts 👁️',
        avatar: 'assets/images/avatar7.png',
      ),
      UserDataModel(
        userId: 'user_008',
        account: 'sifaka_dancer',
        password: '123456',
        userName: 'Nova',
        signature: 'Capturing the graceful dance of sifaka lemurs 💃',
        avatar: 'assets/images/avatar8.png',
      ),
      UserDataModel(
        userId: 'user_009',
        account: 'indri_singer',
        password: '123456',
        userName: 'Echo',
        signature: 'Recording the haunting songs of indri lemurs 🎵',
        avatar: 'assets/images/avatar9.png',
      ),
      UserDataModel(
        userId: 'user_010',
        account: 'mantella_keeper',
        password: '123456',
        userName: 'Zephyr',
        signature: 'Amphibian conservation and colorful frog photography 🐸',
        avatar: 'assets/images/avatar10.png',
      ),
    ]);

    // 更新 Beacon 状态
    allUsersBeacon.value = List.from(_allUsers);
  }

  /// 初始化状态
  static void initialize() {
    _initializeDefaultUsers();
  }

  /// 用户登录
  static bool performUserLogin(String account, String password) {
    try {
      final user = _allUsers.firstWhere(
        (user) => user.account == account && user.password == password,
      );

      _currentUser = user;
      _isLoggedIn = true;
      currentUserBeacon.value = user;
      isLoggedInBeacon.value = true;

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 用户注册
  static bool performUserRegistration({
    required String account,
    required String password,
    required String userName,
    String signature = '',
    String avatar = 'assets/images/avatar1.png',
  }) {
    try {
      // 检查账号是否已存在
      final existingUser = _allUsers.any((user) => user.account == account);
      if (existingUser) {
        return false;
      }

      // 创建新用户
      final newUser = UserDataModel(
        userId: 'user_${DateTime.now().millisecondsSinceEpoch}',
        account: account,
        password: password,
        userName: userName,
        signature:
            signature.isEmpty
                ? 'Welcome to Madagascar wildlife community! 🦎'
                : signature,
        avatar: avatar,
      );

      _allUsers.add(newUser);
      allUsersBeacon.value = List.from(_allUsers);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 退出登录
  static void performUserLogout() {
    _currentUser = null;
    _isLoggedIn = false;
    currentUserBeacon.value = null;
    isLoggedInBeacon.value = false;
  }

  /// 获取当前登录用户信息
  static UserDataModel? getCurrentUserInfo() {
    return _currentUser;
  }

  /// 更新用户信息
  static bool updateUserProfile({
    String? userName,
    String? signature,
    String? avatar,
  }) {
    if (_currentUser == null) return false;

    try {
      final updatedUser = _currentUser!.copyWith(
        userName: userName,
        signature: signature,
        avatar: avatar,
      );

      // 更新当前用户
      _currentUser = updatedUser;
      currentUserBeacon.value = updatedUser;

      // 更新用户列表中的用户信息
      final index = _allUsers.indexWhere(
        (user) => user.userId == updatedUser.userId,
      );
      if (index != -1) {
        _allUsers[index] = updatedUser;
        allUsersBeacon.value = List.from(_allUsers);
      }

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 根据用户ID查询用户信息
  static UserDataModel? queryUserById(String userId) {
    try {
      return _allUsers.firstWhere((user) => user.userId == userId);
    } catch (e) {
      return null;
    }
  }

  /// 根据账号查询用户信息
  static UserDataModel? queryUserByAccount(String account) {
    try {
      return _allUsers.firstWhere((user) => user.account == account);
    } catch (e) {
      return null;
    }
  }

  /// 获取所有用户列表
  static List<UserDataModel> getAllUsersList() {
    return List.from(_allUsers);
  }

  /// 检查用户是否已登录
  static bool checkLoginStatus() {
    return _isLoggedIn;
  }

  // Getters for reactive state
  static ReadableBeacon<UserDataModel?> get currentUser => currentUserBeacon;
  static ReadableBeacon<List<UserDataModel>> get allUsers => allUsersBeacon;
  static ReadableBeacon<bool> get isLoggedIn => isLoggedInBeacon;
}
